#!/usr/bin/env python
# coding=utf-8

"""
Product Helper Utilities

This module provides utility functions for querying and managing product information
for testing purposes.
"""

import os
import sys
import requests
import json

# Add project root to Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))), "tests"))

import config

class ProductHelper:
    """Helper class for product-related operations"""

    def __init__(self):
        self.base_url = f"http://{config.SERVER_IP}:{config.SERVER_PORT}"
        self._cached_products = None

    def get_available_products(self, force_refresh=False):
        """Get list of available products from API"""
        if self._cached_products and not force_refresh:
            return self._cached_products

        try:
            response = requests.get(f"{self.base_url}/symdb/products", timeout=10)

            if response.status_code != 200:
                print(f"Failed to get products: HTTP {response.status_code}")
                return None

            data = response.text
            if data.startswith('{'):
                products_data = json.loads(data)
                products = products_data.get('data', [])
                self._cached_products = products
                return products
            else:
                print(f"Unexpected response format: {data[:100]}...")
                return None

        except Exception as e:
            print(f"Error fetching products: {str(e)}")
            return None

    def get_first_product(self):
        """Get the first available product information"""
        products = self.get_available_products()

        if not products or len(products) == 0:
            print("No products available")
            return None, None

        try:
            first_product = products[0]
            if isinstance(first_product, (list, tuple)) and len(first_product) >= 3:
                # Format: [id, name, version, ...]
                return first_product[1], first_product[2]  # name, version
            else:
                print(f"Unexpected product format: {first_product}")
                return None, None
        except Exception as e:
            print(f"Error parsing product info: {str(e)}")
            return None, None

    def build_modules_url(self, product_name=None, product_version=None):
        """Build modules.html URL with product parameters"""
        if not product_name or not product_version:
            product_name, product_version = self.get_first_product()

        if not product_name or not product_version:
            # Fallback to default modules.html without parameters
            return f"{self.base_url}/modules.html"

        params = f"?product={product_name}&version={product_version}"
        return f"{self.base_url}/modules.html{params}"

    def get_modules_data(self, product_name=None, product_version=None):
        """Get modules data for a specific product"""
        if not product_name or not product_version:
            product_name, product_version = self.get_first_product()

        if not product_name or not product_version:
            print("No product information available")
            return None

        try:
            endpoint = f"/symdb/products/{product_name}/{product_version}/modules"
            response = requests.get(f"{self.base_url}{endpoint}", timeout=15)

            if response.status_code != 200:
                print(f"Failed to get modules data: HTTP {response.status_code}")
                return None

            return response.text

        except Exception as e:
            print(f"Error fetching modules data: {str(e)}")
            return None

    def verify_data_loading(self, product_name=None, product_version=None):
        """Verify that modules data can be loaded successfully"""
        modules_data = self.get_modules_data(product_name, product_version)

        if not modules_data:
            return False, "No modules data available"

        if len(modules_data) < 100:  # Arbitrary minimum for meaningful data
            return False, f"Insufficient data: {len(modules_data)} characters"

        return True, f"Successfully loaded {len(modules_data)} characters of data"

    def verify_test_setup(self):
        """Verify that the test environment is properly set up"""
        products = self.get_available_products()

        if not products:
            print("❌ No products available for testing")
            return False

        product_name, product_version = self.get_first_product()

        if not product_name or not product_version:
            print("❌ Invalid product information")
            return False

        # Verify modules data can be loaded
        success, message = self.verify_data_loading()

        if success:
            print(f"✅ Test setup verified: {product_name}/{product_version}")
            print(f"   {message}")
            return True
        else:
            print(f"❌ Test setup failed: {message}")
            return False

# Global instance for easy access
product_helper = ProductHelper()

def get_test_modules_url():
    """Convenience function to get a test URL for modules.html"""
    return product_helper.build_modules_url()

def verify_test_setup():
    """Verify that the test environment is properly set up"""
    products = product_helper.get_available_products()

    if not products:
        print("❌ No products available for testing")
        return False

    product_name, product_version = product_helper.get_first_product()

    if not product_name or not product_version:
        print("❌ Invalid product information")
        return False

    # Verify modules data can be loaded
    success, message = product_helper.verify_data_loading()

    if success:
        print(f"✅ Test setup verified: {product_name}/{product_version}")
        print(f"   {message}")
        return True
    else:
        print(f"❌ Test setup failed: {message}")
        return False